package me.illtamer.infinite.hook;

import lombok.extern.slf4j.Slf4j;
import me.illtamer.infinite.Translate;
import me.illtamer.infinite.exception.DuplicateAdaptorException;
import me.illtamer.infinite.exception.LengthException;
import me.illtamer.infinite.factory.SingletonFactory;
import me.illtamer.infinite.pojo.Global;
import me.illtamer.infinite.pojo.TransObject;
import me.illtamer.infinite.util.JsonUtil;
import me.illtamer.infinite.util.SecurityUtil;
import org.bukkit.configuration.ConfigurationSection;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class TranslateHook {

    private static final Map<String, TranslatorAdaptor> ADAPTOR_MAP = new HashMap<>();

    /**
     * 测试翻译方法
     * @param srcLang 可为 auto
     * @param trgLang 不可为 auto
     * @apiNote Jsoup会自动将你请求的data进行url编码 真他妈傻逼
     * */
    public static void translate(String srcLang, String trgLang, String context) throws IOException {
        String encode = SecurityUtil.urlEncode(context);
        ConfigurationSection api = Translate.CONFIG.getSection("api-manager");

        Global global = SingletonFactory.getSingleton(Global.class);
        TranslatorAdaptor translator = ADAPTOR_MAP.get(global.getEnabledApi());

        translator.init(global, api);

        int maxLength = translator.getMaxLength();
        if (maxLength != -1 && encode.length() > maxLength)
            throw new LengthException(encode.length());

        String json = translator.translate(context, srcLang, trgLang);
        log.debug(json);

        TransObject object = JsonUtil.getObject(json);
        if (object.getResponse().getCode() != 200) return;

        log.debug(object.toString());
    }

    /**
     * 注册翻译适配器
     * @param name config.yml 内 api-manager 下子节点名称
     * @param adaptor 翻译适配器实例
     * */
    public static void register(String name, TranslatorAdaptor adaptor) {
        if (ADAPTOR_MAP.containsKey(name)) {
            throw new DuplicateAdaptorException(name);
        }
        ADAPTOR_MAP.put(name, adaptor);
    }

    /**
     * 获取全局翻译适配器
     * */
    public static TranslatorAdaptor getGlobalAdaptor(Global global) {
        TranslatorAdaptor adaptor = ADAPTOR_MAP.get(global.getEnabledApi());
        if (adaptor == null)
            throw new RuntimeException("Unregistered global adaptor: " + global.getEnabledApi());
        return adaptor;
    }

}
